<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    title="分配审计任务"
    :visible.sync="visible"
    custom-class="ledger"
    fullscreen top="5vh"
    width="1200px"
    :before-close="cancelDialog">
    <div class="colums">
      <div class="colums_left">
        <div class="colums_left_middle">
          <div class="middleForm ledger">
            <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
              <div class="title">基本信息</div>
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="110px" label="项目名称: " prop="projectName">
                    {{ form.projectName }}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="110px" label="建设单位:">
                    {{ form.auditedCompanyName }}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="140px" label="建设单位联系人:">
                    {{ form.auditedCompanyUserName }}
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">工作安排</div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="协审单位:" prop="assistCompanyName" :rules="{required: true, message: '协审单位不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.assistCompanyName" @focus="showTransferDialog(['assistCompanyId','assistCompanyName'], 'company', false, 3)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="协审单位组长:" prop="assistLeader" :rules="{required: true, message: '协审单位组长不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.assistLeader" @focus="showTransferDialog(['assistLeaderId','assistLeader'], 'user', false, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label-width="110px" label="审计组成员:" prop="assistMembers" :rules="{required: true, message: '审计组成员不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.assistMembers" @focus="showTransferDialog(['assistMemberIds','assistMembers'], 'user', true, form.assistCompanyId)" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
              <el-button icon="el-icon-check" size="small" type="primary" @click="submit">保存</el-button>
                </span>
          </div>
        </div>
      </div>
    </div>
    <FormTransfer :transferDialog="transferDialog" :transferDialogType="transferDialogType" :multiple="transferDialogMultiple" :transferCurrent="transferCurrent" @transferData="transferDataHandle" @closeTransfer="closeTransfer"/>
    <ChoseProject ref="ChoseProject" @setValue="projectDataHandle"/>

  </el-dialog>

</template>

<script>
import FormTransfer from "@/components/form/transfer";
import ChoseProject from "@/components/audited/ChoseProject";
import {getApplyByProjectId, submit} from "@/api/adis/project/projectApply";
import WebDocument from '@/components/form/webDocument.vue';

export default {
  name: 'engineeringApplyForm',
  props: {
    id: {
      type: String,
      default: ''
    },
    projectId: {
      type: String,
      default: ''
    }
  },
  mounted() { // 检测prop中id的值
    if (this.id) { // 如果不为空，开始初始化页面
      this.init({ projectId: this.id });
    } else if (this.projectId){
      this.init({ projectId: this.projectId });
    }
  },
  components: {
    FormTransfer,
    ChoseProject,
    WebDocument
  },
  dictTypes: ['project_progress', 'audit_type', 'audit_type_1_sub', 'audit_way', 'organization_type'],
  data() {
    return {
      visible: false,
      multiple: false,
      transferDialog: false,
      transferDialogType: '',
      transferDialogTypeArr: [],
      transferDialogMultiple: false,
      transferCurrent: {},
      templateForm: [],
      form: {
        auditedCompanyUserName: '',
      },
    }
  },
  watch: {
  },
  methods: {
    init(params) {
      this.$nextTick(() => {
        if (params.projectId) {
          getApplyByProjectId(params.projectId).then(applyResponse => {
            if(applyResponse.data.data.auditStartDate && applyResponse.data.data.auditEndDate) {
              applyResponse.data.data.auditDates = [applyResponse.data.data.auditStartDate, applyResponse.data.data.auditEndDate];
            }
            if(applyResponse.data.data.workStartDate && applyResponse.data.data.workEndDate) {
              applyResponse.data.data.workDates = [applyResponse.data.data.workStartDate, applyResponse.data.data.workEndDate];
            }
            if(applyResponse.data.data.projectStartDate && applyResponse.data.data.projectEndDate) {
              applyResponse.data.data.projectDates = [applyResponse.data.data.projectStartDate, applyResponse.data.data.projectEndDate];
            }
            this.$set(this, "form", applyResponse.data.data);
            this.visible = true;
          })
        }
      })
    },
    showProjectDialog() {
      this.$nextTick(() => {
        this.$refs.ChoseProject.initParams({isEngineering: true, isTermination: false});
      })
    },
    projectDataHandle(row) {
      this.templateForm = this.form
      row.auditDates = [row.auditStartDate, row.auditEndDate];
      row.workDates = [row.workStartDate, row.workEndDate];
      row.projectDates = [row.projectStartDate, row.projectEndDate];
      row.auditStatus = 0
      this.$set(this, "form", Object.assign({}, this.form, row));
    },
    clearProjectForm() {
      this.$set(this, "form", this.templateForm)
    },
    // 表单提交
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          // 将表单中的时间数组分装成对应的开始时间和结束时间
          const dateFields = ['project', 'work'];

          dateFields.forEach(field => {
            const dates = this.form[`${field}Dates`];
            if (dates) {
              this.form[`${field}StartDate`] = dates[0];
              this.form[`${field}EndDate`] = dates[1];
            }
          });
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    //重置表单
    cancelDialog() {
      this.visible = false // 关闭时更改页面显示状态
      this.$emit('cancelDialog', {})
      this.$refs['dataForm'].resetFields()
    },

    showTransferDialog(transferDialogArr, transferDialogType, transferDialogMultiple, transferDialogQuery) {
      this.transferDialogArr = transferDialogArr; // 表单字段
      this.transferDialogType = transferDialogType; // 判断类型user:人员，unit:职位，department:部门,company:单位,plan:计划等
      this.transferDialogMultiple = transferDialogMultiple; // 是否多选
      if (transferDialogType === 'company') {
        this.transferCurrent.type = transferDialogQuery;
      }
      if (transferDialogType === 'user') {
        if(!transferDialogQuery) {
          this.$message({
            type: "warning",
            message: "请先选择单位!"
          });
          return
        }
        this.transferCurrent.deptId = transferDialogQuery;
      }
      //重组数组name和id
      this.transferCurrent.currentval = []
      if(this.form[transferDialogArr[0]]) {
        if (this.form[transferDialogArr[0]].indexOf(',') > -1) {
          this.form[transferDialogArr[0]].split(',').forEach((item, i) => {
            this.transferCurrent.currentval.push({name: this.form[transferDialogArr[1]].split(',')[i], id: item})
          })
        } else {
          this.transferCurrent.currentval = [{name: this.form[transferDialogArr[1]], id: this.form[transferDialogArr[0]]}]
        }
      }
      this.transferDialog = true;
    },
    closeTransfer() {
      this.transferDialog = false
      this.transferDialogType = ''
    },
    // 已选定数据的更新判断
    transferDataHandle(e) {
      this.transferDialog = false
      let currentval = [], currentLabel = []
      if (e.list.length > 0) {
        if (e.list.length > 1) {
          e.list.forEach(item => {
            currentval.push(item.id)
            currentLabel.push(item.name)
          })
        } else {
          currentval = [e.list[0].id]
          currentLabel = [e.list[0].name]
        }
        this.$set(this.form, this.transferDialogArr[0], currentval.join(','))
        this.$set(this.form, this.transferDialogArr[1], currentLabel.join(','))
      } else { // 如果返回的数据为空，也将当前页面数值清空
        this.$set(this.form, this.transferDialogArr[0], '')
        this.$set(this.form, this.transferDialogArr[1], '')
      }
      this.transferDialogType = ''
    },
  }
}
</script>
